package com.handpay.nocardpay.baselibrary.account.view.fragment;


import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.AppCompatCheckBox;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.handpay.nocardpay.baselibrary.DelegateActivity;
import com.handpay.nocardpay.baselibrary.R;
import com.handpay.nocardpay.baselibrary.account.model.bean.Account;
import com.handpay.nocardpay.baselibrary.account.presenter.AccountPresenterImpl;
import com.handpay.nocardpay.baselibrary.account.view.ILoginView;
import com.handpay.nocardpay.baselibrary.account.view.IShowHideFragmentListener;
import com.handpay.nocardpay.baselibrary.commbase.BaseProtocolKey;
import com.handpay.nocardpay.baselibrary.commbase.view.fragment.BaseFragment;
import com.handpay.nocardpay.baselibrary.config.SecureManager;
import com.handpay.nocardpay.baselibrary.permission.PermissionCode;
import com.handpay.nocardpay.baselibrary.permission.PermissionRequest;
import com.handpay.nocardpay.baselibrary.utils.AccountUtils;
import com.handpay.nocardpay.baselibrary.utils.ClientEngine;
import com.handpay.nocardpay.baselibrary.utils.DialogUtils;
import com.handpay.nocardpay.baselibrary.utils.NoCardPayConstant;
import com.handpay.nocardpay.baselibrary.utils.PreferenceManager;
import com.handpay.nocardpay.baselibrary.utils.StatusBarUtil;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;

import java.util.HashMap;
import java.util.List;

/**
 * @author sxshi
 */
public class FastBillLoginFragment extends BaseFragment implements ILoginView, PermissionRequest.onPermissionRequestCallBack {

    private EditText et_account;
    private EditText et_password;

    private Button btn_login;
    private LinearLayout mBackLinearLayout;
    private AppCompatCheckBox mRememberPwd;

    private HashMap<String, Object> paramers;
    private AccountPresenterImpl mLoginLoginPresenter;
    private PermissionRequest mPermissionRequest;

    private String userName, password;
    private boolean isRemindPwd;
    private IShowHideFragmentListener showHideFragmentListener;

    public void setShowHideFragmentListener(IShowHideFragmentListener showHideFragmentListener) {
        this.showHideFragmentListener = showHideFragmentListener;
    }

    public static FastBillLoginFragment newInstance() {
        Bundle args = new Bundle();
        FastBillLoginFragment fragment = new FastBillLoginFragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public int getLayoutId() {
        return R.layout.fragment_fastlogin;
    }

    @Override
    public String getFragmentTitle() {
        return getString(R.string.fastbill_user_title);
    }

    @Override
    public void initView(View view) {
        et_account = (EditText) view.findViewById(R.id.et_account);
        et_password = (EditText) view.findViewById(R.id.et_password);
        btn_login = (Button) view.findViewById(R.id.btn_login);
        mBackLinearLayout = (LinearLayout) view.findViewById(R.id.ll_back);
        mRememberPwd = (AppCompatCheckBox) view.findViewById(R.id.remenberpwd);
    }

    @Override
    public void setStatusBar(View view) {
        super.setStatusBar(view);
        StatusBarUtil.setTranslucentForImageViewInFragment(_mActivity, 0, null);
    }

    @Override
    public void initListener() {
        btn_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                hideSoftInput();
                userName = et_account.getText().toString();
                password = et_password.getText().toString();
                if (TextUtils.isEmpty(userName)) {
                    DialogUtils.showToast(_mActivity, _mActivity.getString(R.string.hint_please_input_phone_no));
                    return;
                }
//                if (!CommonUtils.isMobileNum(userName)) {
//                    DialogUtils.showToast(_mActivity, _mActivity.getString(R.string.input_right_phone_tip));
//                    return;
//                }

                if (TextUtils.isEmpty(password)) {
                    DialogUtils.showToast(_mActivity, _mActivity.getString(R.string.no_input_password));
                    return;
                }
                if (!AccountUtils.isPwdLegal(password)) {
                    DialogUtils.showToast(_mActivity, _mActivity.getString(R.string.illegal_input_password));
                    return;
                }
                mPermissionRequest.requestPermission(Permission.PHONE, Permission.STORAGE);
            }
        });

        mRememberPwd.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                PreferenceManager.getInstance(_mActivity).putBoolean(BaseProtocolKey.ISREMEMBER, isChecked);
            }
        });

        mBackLinearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showHideFragmentListener.showFragment(NoCardPayConstant.NOCARDPAY_LOGIN);
            }
        });
    }

    /**
     * 秒秒通登录
     */
    private void fastBillLogin() {
        paramers.put(BaseProtocolKey.ACCOUNT, SecureManager.getInstance().des(userName, 1, null));
        paramers.put(BaseProtocolKey.PWD, SecureManager.getInstance().des(password, 1, null));
        paramers.put(BaseProtocolKey.CHANNEL, ClientEngine.getInstance().FASTBILLCHANNEL);
        paramers.put(BaseProtocolKey.LOGINCHANNEL, "1");
        isRemindPwd = mRememberPwd.isChecked();
        PreferenceManager.getInstance(_mActivity).putBoolean(BaseProtocolKey.ISREMEMBER, isRemindPwd);
        mLoginLoginPresenter.fastbillLogin(paramers, Account.class, true);
    }

    @Override
    public void navigateToHome() {
        if (isRemindPwd) {
            AccountUtils.saveRMSAccountPWD(password);
        }
        ClientEngine.getInstance().saveRMSData(BaseProtocolKey.FASTBILL_NAME, userName);
        _mActivity.startActivity(new Intent(_mActivity, DelegateActivity.class));
        _mActivity.finish();
    }

    @Override
    public void loginError(String errorMsg) {
        DialogUtils.showAlertDialog(_mActivity, _mActivity.getString(R.string.dialog_title), errorMsg, false);
    }

    @Override
    public void noSessionId() {
        DialogUtils.showAlertDialog(_mActivity, _mActivity.getString(R.string.dialog_title), _mActivity.getString(R.string.login_fail), false, _mActivity.getString(R.string.dialog_ok), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                _mActivity.finish();
            }
        });
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        paramers = new HashMap<>();
        mLoginLoginPresenter = new AccountPresenterImpl(_mActivity);
        mLoginLoginPresenter.setmLoginView(this);
        mPermissionRequest = new PermissionRequest(_mActivity, this);
        isRemindPwd = PreferenceManager.getInstance(_mActivity).getBoolean(BaseProtocolKey.ISREMEMBER, false);
        if (isRemindPwd) {
            password = AccountUtils.getRMSAccountPwd();
            if (!TextUtils.isEmpty(password)) {
                et_password.setText(password);
            }
        } else {
            AccountUtils.removeRMSPWDData();
        }
        userName = ClientEngine.getInstance().getRMSData(BaseProtocolKey.FASTBILL_NAME);
        if (!TextUtils.isEmpty(userName)) {
            et_account.setText(userName);
        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case PermissionCode.REQUEST_CODE_SETTING: {
                if (AndPermission.hasPermission(_mActivity, Permission.PHONE) && AndPermission.hasPermission(_mActivity, Permission.STORAGE)) {
                    fastBillLogin();
                }
                break;
            }
        }
    }

    @Override
    public void permissionYes(List<String> permissions) {
        fastBillLogin();
    }

    @Override
    public void permissionFail(List<String> permissions) {
        // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
        if (AndPermission.hasAlwaysDeniedPermission(_mActivity, permissions)) {
            // 第一种：用默认的提示语。
            AndPermission.defaultSettingDialog(FastBillLoginFragment.this, PermissionCode.REQUEST_CODE_SETTING).show();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mLoginLoginPresenter.onDestory();
    }

}
